package com.ubao.activity;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ubao.R;
import com.ubao.activity.MyApp.GoBack;
import com.ubao.base.RequestBaseActivity;
import com.ubao.bean.Category;
import com.ubao.bean.ListCategory;
import com.ubao.dialog.CamreaDialog;
import com.ubao.dialog.OnDialogListeren;
import com.ubao.network.HttpHelper;
import com.ubao.network.JsonParser;
import com.ubao.network.ResponseInterface;
import com.ubao.network.Url;
import com.ubao.network.req.SpecialRequest;
import com.ubao.network.resp.SpecialResponse;
import com.ubao.ui.titlebar.GTitleBar;
import com.ubao.ui.togglebutton.ToggleButton;
import com.ubao.util.Helper;
import com.ubao.util.Util;
import com.ubao.util.log.Logger;

public class PostProductActivity extends RequestBaseActivity implements OnClickListener{
	public static final int NONE = 0;
	public static final int PHOTOHRAPH = 1;// 拍照
	public static final int PHOTOZOOM = 2; // 缩放
	public static final int PHOTORESOULT = 3;/// 结果
	public static final String IMAGE_UNSPECIFIED = "image/*";
	
	ImageView ivProductImg;
	GTitleBar mTitleBar;
	CamreaDialog camreaDialog;//拍照选项Dialog
	Bitmap photo;
	Map<String,File> mapFiles;
	
	
	
//	private String title;//			string			标题
//	private String desc;//			string			描述
//	private String duration;//		int				有效天数
//	private String pclass;	//		string			产品的分类
//	private String isprivate;//			string			是否为私人（0为不私有，1为私有）
//	private String swap;	//		string			是否交换（0为不交换，1为交换）
//	private String share;	//		string			是否分享（0为不分享，1为分享）
	//参数：img			Binary			图片内容（仅支持JPEG,GIF,PNG格式，图片小于2M）
	
	//private RelativeLayout rlbegintime;
	private RelativeLayout rlendtime;
	private RelativeLayout rCategory;
	private EditText etTitle;
	private EditText etDesc;
	private ToggleButton tbExchange;
	private ToggleButton tbIsPrivate;
	private RelativeLayout rlShare;
	private Calendar c = null;
	private static List<Category> listcategory;
	private TextView tvChooseCategory;
	private TextView tvChooseTimeXJ;
	private CharSequence[] arrayduring = new CharSequence[]{"5","10","15","20","25","30"};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ui_postproduct);
		initViews();
	}
	private void initViews() {
		// TODO Auto-generated method stub
		ivProductImg = (ImageView) findViewById(R.id.ivProductImg);
		ivProductImg.setOnClickListener(this);
		//rlbegintime = (RelativeLayout) findViewById(R.id.rlbeigntime);
		rlendtime = (RelativeLayout) findViewById(R.id.rlendtime);
		rCategory = (RelativeLayout) findViewById(R.id.rCategory);
		etTitle = (EditText) findViewById(R.id.etProductTitle);
		etDesc = (EditText) findViewById(R.id.etProductDesc);
		tbExchange = (ToggleButton) findViewById(R.id.tbExchange);
		tbIsPrivate = (ToggleButton) findViewById(R.id.tbIsPrivate);
		tvChooseCategory = (TextView) findViewById(R.id.tvChooseCategory);
		tvChooseTimeXJ = (TextView) findViewById(R.id.tvChooseTimeXJ);
		mTitleBar = (GTitleBar)findViewById(R.id.mTitleBar);
	    mTitleBar.initLeftButton("", R.drawable.titlebar_back, this);
	    mTitleBar.initRightButton("发布", R.drawable.titlebar_button_bg, this);
	    mTitleBar.initTitle("添加商品");
	        
	     camreaDialog = new CamreaDialog(this,R.style.CustomDialogStyle);//创建Dialog并设置样式主题
	     camreaDialog.setOnDialogListeren(onDialogListeren);
	     
	     rCategory.setOnClickListener(this);
	     rlendtime.setOnClickListener(this);
	     tvChooseTimeXJ.setText(getEndDate("5"));
	     if(listcategory==null){
	    	 sendCateGoryRequest();
	     }
	     
	}
	
	private void sendCateGoryRequest() {
		startProgress();
		SpecialRequest request = new SpecialRequest(Url.url_categorylist_full);
		request.msg_id = 0;
		request.encoding = "utf-8";
		mHttpHandler.sendRequest(request);
	}
	
	private String userid = MyApp.weiboUser.userid;
	private String title = "";
	private String desc = "";
	private String typeid = "";
	private String typename = "";
	private String exchange = "0";
	private String isPrivate = "0";
	private String longititude = "";
	private String latitude = "";
	private String shelftime = "";
	private String releasetime = "";
	
	private void getValues(){
		userid = MyApp.weiboUser.userid;
		title = etTitle.getText().toString().trim();
		desc = etDesc.getText().toString().trim();
		typeid = "1";
		typename = "生活用品";
		exchange = tbExchange.isChecked()?"1":"0";
		isPrivate = tbIsPrivate.isChecked()?"1":"0";
		longititude = MyApp.locationManager.longtitude;
		latitude =  MyApp.locationManager.latitude;
		shelftime = getDateNow();
		releasetime = "";
	}
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v.getId()==mTitleBar.getLeftButton().getId()){
			GoBack.goBack(this);
		}else if(v.getId()==mTitleBar.getRightButton().getId()){
			if(!validate()){
				return;
			}
			getValues();
			Map<String,String> params = Url.getCommodityadd(this, userid, title, desc, typeid, typename, exchange, longititude, latitude, shelftime, releasetime);
			Map<String,File> files = Util.writeBitmap("catemain0.jpg", photo);
			SpecialRequest request = HttpHelper.getMultPartRequest(Url.url_commodityadd_full, params, files);
			request.msg_id = 1;
			mHttpHandler.sendRequest(request);
		}else if(v.getId()==ivProductImg.getId()){
			camreaDialog.show();
		}else if(v.getId()==rCategory.getId()){
			if(listcategory==null){
				showToast("正在获取类别，请稍候");
			}else{
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("选择类别").setItems(arrayTypeNames(), new DialogInterface.OnClickListener() {
	
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						typeid = listcategory.get(which).getTypeID();
						typename = listcategory.get(which).getTypeName();
						tvChooseCategory.setText(typename);
					}
				}).create().show();
			}
		}else if(v.getId()==rlendtime.getId()){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("下架时间").setItems(arrayduring, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					releasetime = getEndDate(arrayduring[which]);
					tvChooseTimeXJ.setText(releasetime);
				}

				
			}).create().show();
		}
	}
	
	private String getEndDate(CharSequence charSequence) {
		GregorianCalendar gc = new GregorianCalendar();
		gc.add(Calendar.DAY_OF_MONTH, Integer.parseInt(String.valueOf(charSequence)));
		return gc.get(Calendar.YEAR) + "-" + (gc.get(Calendar.MONTH)+1) + "-" + gc.get(Calendar.DATE);
	}
	
	private String getDateNow() {
		GregorianCalendar gc = new GregorianCalendar();
		return gc.get(Calendar.YEAR) + "-" + (gc.get(Calendar.MONTH)+1) + "-" + gc.get(Calendar.DATE);
	}
	
	private CharSequence[] arrayTypeNames(){
		CharSequence[] a = new String[listcategory.size()];
		for(int i=0;i<listcategory.size();i++){
			a[i] = listcategory.get(i).getTypeName();
		}
		return a;
	}

	 private boolean validate() {
		 if(etTitle.getText().toString().trim().equals("")){
			 showToast("请填写标题");
			 return false;
		 }else if(etDesc.getText().toString().trim().equals("")){
			 showToast("请填写描述");
		 }else if(MyApp.locationManager.point==null){
			 if(!MyApp.locationManager.checkIsEnableLocation()){
				 showToast("无法获取您的位置，请到设置中打开位置信息来源");
			 }else{
				 showToast("正在定位，请稍候");
			 }
			 return false;
		 }else if(photo==null){
			 showToast("请为您的物品拍张照！");
			 return false;
		 }
		return true;
	}
	 

	OnDialogListeren onDialogListeren = new OnDialogListeren(){

			@Override
			public void OnClick(Dialog arg0, View arg1, int arg2, boolean arg3,
					Object arg4) {
				//锟斤拷锟斤拷Dialog
				if(arg0 instanceof CamreaDialog)
				{
					camreaDialog.dismiss();
					switch(arg1.getId())
					{
					case R.id.photo_make:
												
						Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(
								Environment.getExternalStorageDirectory(), "temp.jpg")));
						startActivityForResult(intent1, PHOTOHRAPH);
							break;
					case R.id.photo_album:

						Intent intent2 = new Intent(Intent.ACTION_PICK, null);
						intent2.setDataAndType(
								MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
								IMAGE_UNSPECIFIED);
						startActivityForResult(intent2, PHOTOZOOM);
						
							break;
					case R.id.btnCancel:
						camreaDialog.dismiss();
						break;
						}
					
					}
				
			}

			@Override
			public void setTextViewContent(Dialog dialog, View view) {
				// TODO Auto-generated method stub
				
			}};
			
			
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			if (resultCode == NONE)
				return;
			// 拍照
			if (requestCode == PHOTOHRAPH) {
				// 设置文件保存路径这里放在跟目录下
				File picture = new File(Environment.getExternalStorageDirectory()
						+ "/temp.jpg");
				System.out.println("拍照"+Uri.fromFile(picture));
				startPhotoZoom(Uri.fromFile(picture));
			}

			if (data == null)
				return;

			// 读取相册缩放图片
			if (requestCode == PHOTOZOOM) {
				System.out.println("相册"+data.getData());
				startPhotoZoom(data.getData());
			}
			// 处理结果
			if (requestCode == PHOTORESOULT) {
				Bundle extras = data.getExtras();
				if (extras != null) {
					
					 photo = extras.getParcelable("data");
					 mapFiles=Helper.saveSDCard(photo);				
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 -
					// 100)压缩文件
					
					//显示处理后的图片
					//ivPhotoShow.setLayoutParams(new RelativeLayout.LayoutParams(40,40));
					ivProductImg.setImageBitmap(photo);				
				}

			}
			super.onActivityResult(requestCode, resultCode, data);
		}
		
		public void startPhotoZoom(Uri uri) {
			Intent intent = new Intent("com.android.camera.action.CROP");
			intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
			intent.putExtra("crop", "true");
			// aspectX aspectY 是宽高的比例
			//intent.putExtra("aspectX", 1);
			//intent.putExtra("aspectY", 1);
			// outputX outputY 是裁剪图片宽高
			intent.putExtra("outputX", 300);
			intent.putExtra("outputY", 320);
			intent.putExtra("return-data", true);
			startActivityForResult(intent, PHOTORESOULT);
		}
		@Override
		protected void httpCompleted(ResponseInterface resp) {
			// TODO Auto-generated method stub
			SpecialResponse response = (SpecialResponse)resp;
			if(response.msg_id==0){
				ListCategory list = JsonParser.getListCategory(response.content);
				if(list.getStatus().equals(Url.SUCCESS)){
					listcategory = list.getListCategory();
					handler.sendEmptyMessage(0);
					Logger.d("" + listcategory);
				}else{
					Message msg = handler.obtainMessage();
					msg.obj = list.getMessage();
					msg.what = 1;
					handler.sendMessage(msg);
				}
			}else if(response.msg_id==1){
				showToast("发布成功！");
				GoBack.goBack(this);
			}
		}
		
		Handler handler = new Handler(){

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				closeProgress();
				if(msg.what==1){
					showToast((String)msg.obj);
				}
			}
			
		};
		@Override
		protected void initView() {
			// TODO Auto-generated method stub
			
		}
		@Override
		protected void getIntentData() {
			// TODO Auto-generated method stub
			
		}
		@Override
		protected void setIntentData() {
			// TODO Auto-generated method stub
			
		}

			
}
